package com.funo.ehealth.thread;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.funo.ehealth.dao.UserOrderDao;
import com.funo.ehealth.exception.UnCaughtException;
import com.funo.ehealth.main.ListMgr;

/** 
 * CP订购关系同步信息读取线程
 * 
 * @version V1.1
 * @author zhangguangying
 * @date 2013-2-1
 */
public class CPOrderReadThread extends AbstractThread {
	
	/**
	 * CP订购关系同步线程日志记录器
	 */
	private static final Log log = LogFactory.getLog(CPOrderReadThread.class);
	/**
	 * 间隔时间
	 */
	private static final long INTERVAL = 5000L;
	/**
	 * 线程运行标识
	 */
	public boolean isRunning = true;
	
	public CPOrderReadThread(ThreadGroup group, String name) {
		super(group, name);
		// TODO Auto-generated constructor stub
	}
	
	/* (non-Javadoc)
	 * @see com.funo.ehealth.thread.AbstractThread#init()
	 */
	@Override
	public boolean init() {
		boolean result = true;
		log.info("初始化CP订购关系同步信息读取线程...");
		return result;
	}

	/* (non-Javadoc)
	 * @see com.funo.ehealth.thread.AbstractThread#terminateHandler()
	 */
	@Override
	public void terminateHandler() {
		log.info("退出CP订购关系同步信息读取线程...");
		isRunning = false;
		ListMgr.cpOrderList.clear();
		
		synchronized (ListMgr.cpOrderList) {
			try{
				ListMgr.cpOrderList.notifyAll();
			}catch (IllegalMonitorStateException e) {
				log.error("CP订购关系同步信息读取线程ListMgr.cpOrderList.notifyAll()异常", e);
			}
		}
	}

	@Override
	public void run() {
		log.info("启动CP订购关系同步信息读取线程...");
		
		UserOrderDao userOrderDao = new UserOrderDao();
		
		while (isRunning) {
			synchronized (ListMgr.cpOrderList) {
				if(ListMgr.cpOrderList != null && ListMgr.cpOrderList.size() > 0){
					ListMgr.cpOrderList.notify();
					
					try {
						ListMgr.cpOrderList.wait();
					} catch (InterruptedException e) {
						log.error("CP订购关系同步信息读取线程ListMgr.cpOrderList.wait()异常",e);
						throw new UnCaughtException();
					}
				}
			}
			
			userOrderDao.queryUserOrderList(ListMgr.cpOrderList);
			
			try {
				sleep(INTERVAL);
			} catch (InterruptedException e) {
				log.error("CP订购关系同步信息读取线程sleep异常" , e);
				throw new UnCaughtException();
			}
		}
	}

}
